
import { _decorator, Component, error, Node } from 'cc';
import { GameCtrl } from './GameCtrl';
import { ByteBuffer } from './ByteBuffer';
const { ccclass, property } = _decorator;

 
@ccclass('NetSocket')
export class NetSocket extends Component {

    serverURL: 'ws://47.107.71.29:12345'
    socket: WebSocket = null

    static Instance : NetSocket = null;

    protected onLoad(): void {

        if(!NetSocket.Instance)
        {
            NetSocket.Instance = this;
        }
        else
        {
            return ;
        }
    }

    start () {
        this.InitWebSocketConnection();
    }

    private InitWebSocketConnection(){
        this.socket = new WebSocket('ws://47.107.71.29:9999');
        this.socket.binaryType = 'arraybuffer'

        this.socket.onopen = (e)=> {
            console.log('WebSocket连接已打开');
            this.DoSend("123456789");
        };

        this.socket.onmessage = (event)=> {
            this.DoReceive(event.data);
        };

        this.socket.onclose = (event)=>{
            console.log('连接断开');
        }

        this.socket.onerror = (error)=>{

        }        
    }

    CloseWebSocketConnection() {
        if (this.socket) {
            this.socket.close();
        }
    }

    receive = [];
    length = 0;
    DoReceive(buffer) {
        console.log('buffer data: ',buffer);
        this.receive = this.receive.concat(Array.from(new Uint8Array(buffer)));
        if (this.receive.length < 4) {
            return;
        }
        length = new DataView(new Uint8Array(this.receive).buffer).getUint16(0,true);
        if (this.receive.length < length) {
            return;
        }
        let opcode = 0
        opcode = new DataView(new Uint8Array(this.receive).buffer).getUint16(2,true);

        var bytes = this.receive.slice(4, length);

        //转为buffer
        var dataBuffer = new ByteBuffer(bytes.length);
        dataBuffer.setBufferData(new Uint8Array(bytes).buffer);

        let cbFunc = GameCtrl.Instance.GetCBFuncByOpcode(opcode);
        if(cbFunc)
        {
            cbFunc(dataBuffer);
        }

        this.receive = this.receive.slice(length);
    };

    DoSend(bytes) {
        var buffer = new ArrayBuffer(bytes.length + 4);
        var view = new DataView(buffer);
        view.setUint16(0, bytes.length + 4,true); 
        view.setUint16(2, 1,true);//opcode uint16
        for (var i = 0; i < bytes.length; i++) {
            view.setUint8(i + 4, bytes[i]);
        }
        console.log("view: ",view);
        this.socket.send(view);
    };

    // 程序关闭时调用
    onDestroy() {
        this.CloseWebSocketConnection();
    }
}
